package com.vmj.heap;

import com.vmj.classfile.entity.MemberInfo;
import com.vmj.classfile.entity.attribute.ConstantValueAttribute;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by yangshoujun on 2017/8/26 下午12:29.
 */
public class Field extends ClassMember {

    private int slotId;
    private int constValueIndex;

    public static List<Field> parseField(VMClass clazz, List<MemberInfo> cfFields) {

        List<Field> fields = new ArrayList<Field>();
        for(int i = 0; i < cfFields.size();i++) {
            Field field = new Field();
            field.copyMemberInfo(cfFields.get(i));
            field.copyAttributes(cfFields.get(i));
            field.setClazz(clazz);

            fields.add(field);
        }

        return fields;
    }

    public void copyAttributes(MemberInfo cfField) {
        ConstantValueAttribute valAttr = cfField.getConstantValueAttribute();
        if(valAttr != null) {
            this.constValueIndex = valAttr.getConstantValueIndex();
        }
    }

    public VMClass getType() {
        String className = ClassUtils.toClassName(descriptor);
        return clazz.getClassLoader().loadClass(className);
    }

    public int getSlotId() {
        return slotId;
    }

    public void setSlotId(int slotId) {
        this.slotId = slotId;
    }

    public boolean isVolatile() {
        return 0 != (this.accessFlags & AccessFlag.ACC_VOLATILE);
    }

    public boolean isTransient() {
        return 0 != (this.accessFlags & AccessFlag.ACC_TRANSIENT);
    }

    public boolean isEnum() {
        return 0 != (this.accessFlags & AccessFlag.ACC_ENUM);
    }

    public boolean isLongOrDouble() {
        return "J".equals(this.descriptor) || "D".equals(this.descriptor);
    }

    public int getConstValueIndex() {
        return constValueIndex;
    }

    public void setConstValueIndex(int constValueIndex) {
        this.constValueIndex = constValueIndex;
    }

    @Override
    public String toString() {
        return "Field{" +
                "name='" + name + '\'' +
                ", descriptor='" + descriptor + '\'' +
                ", clazz=" + clazz +
                '}';
    }
}
